<?php
namespace cms\modules\frontend\controllers;

use Yii;
use app\models\DynamicData;
use app\models\DynamicDataInfo;
use app\models\DynamicDataList;
use app\models\DynamicDataFlag;
use app\models\MemberStar;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\component\tool\ImageUpload;
use common\component\tool\Member;

class DynamicDataController extends AuthController
{
    /*添加数据*/
    public function actionAdd()
    {
        if(isset($this->post['id'])){
            $dynamicData = DynamicData::find()
                ->select(['{{%dynamic_data}}.dynamic_id', 'name', 'defaultflagnum', 'is_member', 'send_integral', 'integral', 'max_integral', 'max_times', 'data_count', 'audit'])
                ->joinWith('attr')
                ->where('{{%dynamic_data}}.app_id = :app_id and {{%dynamic_data}}.dynamic_id=:id and display=2', [':app_id' => $this->app_id, ':id' => $this->post['id']])
                ->asArray()->one();
            if(!is_null($dynamicData)){
                // P($this->isLogin());
                // P($this->memberInfo);
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    if($dynamicData['is_member'] == 2){//必须要登录
                        if(!$this->isLogin()){//没登录
                            return Tool::showRes(ErrMap::getError(10007));
                        }else{
                            if($this->upperLimit($dynamicData)){

                            }
                            // P('ok');
                            /*1、录入数据*/
                            if(($res = $this->addData($dynamicData, $this->memberInfo->member_id)) !== true){
                                return $res;
                            }

                            /*2、添加积分 ，满足条件的情况下 条件一：需要发积分 条件二：不超过每人每天的最高发放积分*/
                            if($dynamicData['send_integral'] == 2){
                                if(($res = $this->addIntegral($dynamicData, $this->memberInfo->member_id)) !== true){
                                    return $res;
                                }
                            }

                        }
                    }else{//无需登录
                        if(!$this->upperLimit($dynamicData)){
                            $err = ErrMap::getError(10005);
                            $err[1] = '每天最多提交'. $dynamicData['max_times'] .'次';
                            return Tool::showRes($err);
                        }
                        // P('ok');
                        /*录入数据*/
                        if($this->isLogin()){//如果登录了，需要把会员ID放进去
                            if(($res = $this->addData($dynamicData, $this->memberInfo->member_id)) !== true){
                                return $res;
                            }
                        }else{
                            if(($res = $this->addData($dynamicData)) !== true){
                                return $res;
                            }
                        }
                    }

                    if($pass){
                        $backInfo = [0, '提交成功'];//返回信息
                        $transaction->commit();
                        return Tool::showRes($backInfo);
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();       
                };
            }
        }
        return Tool::showRes(ErrMap::getError(10005));
    }


    /*上传图片*/
    public function actionUploadPic()
    {
        // P($this->post);
        // P($_FILES);
        // P($this->app_id);
        // P($this->memberInfo);
        if(isset($this->post['id'])){
            $dynamicData = DynamicData::find()
                    ->select(['{{%dynamic_data}}.dynamic_id', 'name', 'is_member', 'send_integral', 'integral', 'max_integral', 'max_times', 'data_count', 'audit'])
                    ->joinWith('attr')
                    ->where('{{%dynamic_data}}.app_id = :app_id and {{%dynamic_data}}.dynamic_id=:id and display=2', [':app_id' => $this->app_id, ':id' => $this->post['id']])
                    ->asArray()->one();
            // P($dynamicData);
            /*查看是否有图片上传*/
            $has = false;
            if(!empty($dynamicData['attr'])){
                foreach($dynamicData['attr'] as $k => $v){
                    // P($v);
                    if($v['attr_type'] == 7){
                        $has = true;
                    }
                }
            }

            if($has){//可上传
                $imageUpload = new ImageUpload();
                $this->post['catId'] = 0;
                return $imageUpload->upload($this->post, $this->appid, 0, $this->app_id);
            }
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*
    判断是否达到当天的上线
    $dynamicData    动态规则数据
    $memberId     会员登录数据
    */
    private function upperLimit($dynamicData, $memberId = 0)
    {
        // P($dynamicData);
        if($memberId == 0){//无需登录
            $count = DynamicDataInfo::find()->where('sessionid = :sessionid and client = :client', [':sessionid' => session_id(), ':client' => $_SERVER['HTTP_USER_AGENT']])->count();
            if($count >= $dynamicData['max_times']){
                // P($count . '-' . $dynamicData['max_times']);
                return false;
            }
        }

        return true;
    }

    /*
    添加数据
    $dynamicData    动态规则数据
    $memberId     会员登录数据
    */
    private function addData($dynamicData, $memberId = 0)
    {
        // P($dynamicData);
        // P($this->post);
        /*
        1、排除后台没有设置的数据
        2、判断后台不准为空的数据
        3、如果可以为空，后台有默认值的放默认值
        */
        foreach($this->post as $k => $v){
            $has = false;
            foreach($dynamicData['attr'] as $k1 => $v2){
                if($k == $v2['attr_enname']){
                    $has = true;
                    /*2、如果后台不能为空的话，判断是否为空，为空直接打回*/
                    if($v2['can_null'] == 1 and empty($v)){
                        $err = ErrMap::getError(10005);
                        $err[1] = $v2['attr_name'] . '不能为空！';
                        return Tool::showRes($err);
                    }
                    /*3、如果可以为空的话，后台也设置了默认值，把默认值放上去*/
                    if($v2['can_null'] == 2 and empty($v)){
                        $this->post[$k] = $v2['default_val'];
                    }
                }
            }
            if(!$has){
                /*1、排除后台没有设置的数据*/
                unset($this->post[$k]);
            }
        }
        // P($this->post);

        /*添加到 su_cms_dynamic_data_info*/
        $dynamicDataInfo = new DynamicDataInfo;
        $data = array(
            'DynamicDataInfo' => array(
                'dynamic_id' => $dynamicData['dynamic_id'],
                'flagnum' => $dynamicData['defaultflagnum'],
                'member_id' => $memberId,
                'ip' => Yii::$app->request->userIP,
                'sessionid' => session_id(),
                'client' => $_SERVER['HTTP_USER_AGENT'],
                'state' => ($dynamicData['audit'] == 2)?1:2,
                'add_time' => date('Y-m-d H:i:s', time()),
            )
        );
        if($dynamicDataInfo->addData($data, $this->app_id)){
            $infoid = $dynamicDataInfo->getPrimaryKey();
        }else{
            if($dynamicDataInfo->hasErrors()){
                $exception = $dynamicDataInfo->getErrors();//异常信息
                // return $exception;
                $err = ErrMap::getError(10005);
                foreach($exception as $k1 => $v2){
                    $err[1] = $exception[$k1][0];
                    return Tool::showRes($err);
                }
            }
        }

        /*添加到 su_cms_dynamic_data_list*/
        foreach($this->post as $k => $v){
            $data = array(
                'DynamicDataList' => array(
                    'info_id' => $infoid,
                    'dynamic_id' => $dynamicData['dynamic_id'],
                    'attr_enname' => $k,
                    'attr_value' => $v,
                )
            );
            // P($data, false);
            $dynamicDataList = new DynamicDataList;
            if(!$dynamicDataList->addData($data)){
                if($dynamicDataList->hasErrors()){
                    $exception = $dynamicDataList->getErrors();//异常信息
                    // P($exception);
                    $err = ErrMap::getError(10005);
                    foreach($exception as $k1 => $v2){
                        $err[1] = $exception[$k1][0];
                        return Tool::showRes($err);
                    }
                }
            }
        }

        /*增加数据总数*/
        DynamicData::updateAllCounters(['data_count' => 1], 'dynamic_id = :id', [':id' => $dynamicData['dynamic_id']]);

        return true;
    }

    /*
    添加积分
    $dynamicData    动态规则数据
    $memberId       会员登录数据
    */
    private function addIntegral($dynamicData, $memberId = 0)
    {
        return true;
    }

    /*
    动态数据内容列表
    flag    all(全部都取) member(取自己提交的，但必须登录后)
    */
    public function actionDynamicDataInfoList()
    {
        if(isset($this->get['id']) and is_numeric($this->get['id'])){

            if(isset($this->get['page'])){
                $currPage = intval($this->get['page']?$this->get['page']:1);
            }else{
                $currPage = 1;
            }
            $pageSize = isset($this->get['pageSize'])?intval($this->get['pageSize']):Tool::getPageSize();
            if($pageSize > Yii::$app->params['maxPageSize']){
                $pageSize = Yii::$app->params['maxPageSize'];
            }
            // P($pageSize);
            $andWhere = '';
            if(isset($this->get['flagnum']) and
                (int)$this->get['flagnum'] > 0 and
                (int)$this->get['flagnum'] <= count(Yii::$app->params['dynamicRule']['groupToOrigin'])){
                $andWhere = 'flagnum = ' . (int)$this->get['flagnum'];
            }

            $dynamicDataInfo = new DynamicDataInfo;
            /*如果有openid, 则可以获取用户信息，实现登录*/
            if(!$this->isLogin() 
                and isset($this->get['openid'])){
                $this->getinfoByOpenid($this->get['openid'], $this->comid);
            }
            
            /*如果flag==member 且登录了，取自己都提交的内容 */
            if(isset($this->get['flag']) and 
                $this->get['flag'] == 'member' and 
                $this->isLogin()){
                $count = $dynamicDataInfo::find()
                                ->where('app_id = :app_id and dynamic_id = :id and member_id = :mid and state = 2', [':app_id' => $this->app_id, ':id' => $this->get['id'], ':mid' => $this->memberInfo->member_id])
                                ->andWhere($andWhere)
                                ->count();
                $dynamicDataInfoList = $dynamicDataInfo::find()
                                ->select(['info_id', 'dynamic_id', 'flagnum', 'member_id', 'star_num', 'praise_num', 'reply_num', 'add_time'])
                                ->where('app_id = :app_id and dynamic_id = :id and member_id = :mid and state = 2', [':app_id' => $this->app_id, ':id' => $this->get['id'], ':mid' => $this->memberInfo->member_id])
                                ->andWhere($andWhere)
                                ->with('content')
                                ->with('attrName')
                                ->orderBy([
                                    'add_time' => SORT_DESC
                                ])
                                ->offset($pageSize*($currPage-1))->limit($pageSize)
                                ->asArray()->all();

            }else{            
                $count = $dynamicDataInfo::find()
                                ->where('app_id = :app_id and dynamic_id = :id and state = 2', [':app_id' => $this->app_id, ':id' => $this->get['id']])
                                ->andWhere($andWhere)
                                ->count();
                $dynamicDataInfoList = $dynamicDataInfo::find()
                                ->select(['info_id', 'dynamic_id', 'flagnum', 'member_id', 'star_num', 'praise_num', 'reply_num', 'add_time'])
                                ->where('app_id = :app_id and dynamic_id = :id and state = 2', [':app_id' => $this->app_id, ':id' => $this->get['id']])
                                ->andWhere($andWhere)
                                ->with('content')
                                ->with('attrName')
                                ->orderBy([
                                    'add_time' => SORT_DESC
                                ])
                                ->offset($pageSize*($currPage-1))->limit($pageSize)
                                ->asArray()->all();
            }

            // P($dynamicDataInfoList);


            /*收集info_id，取出会员是否收藏、点赞*/
            if(!is_null($dynamicDataInfoList) 
                and $this->isLogin()){
                $info_ids = [];
                foreach($dynamicDataInfoList as $k => $v){
                    array_push($info_ids, $v['info_id']);
                }
                $memberStarList = MemberStar::find()->select(['sflag', 'contentid'])
                                        ->where('app_id = :app_id and cflag=2 and member_id = :mid', [':app_id' => $this->app_id, ':mid' => $this->memberInfo->member_id])
                                        ->asArray()->all();
                if(!is_null($memberStarList)){
                    $star = [];
                    $praise = [];
                    foreach($memberStarList as $k => $v){
                        if($v['sflag'] == 1){//收藏
                            array_push($star, $v['contentid']);
                        }
                        if($v['sflag'] == 2){//点赞
                            array_push($praise, $v['contentid']);
                        }
                    }
                    foreach($dynamicDataInfoList as $k => $v){
                        $dynamicDataInfoList[$k]['star'] = false;
                        $dynamicDataInfoList[$k]['praise'] = false;
                        if(in_array($v['info_id'], $star)){
                            $dynamicDataInfoList[$k]['star'] = true;
                        }
                        if(in_array($v['info_id'], $praise)){
                            $dynamicDataInfoList[$k]['praise'] = true;
                        }
                    }
                }
            }

            /*取出标示数据*/
            $dynamicDataFlag = DynamicDataFlag::find()
                               ->select('flagname')
                               ->where('dynamic_id = :id', [':id' => $this->get['id']])
                               ->asArray()->one();
            // P($dynamicDataFlag);
            $flagname = '';
            if(!is_null($dynamicDataFlag) and !empty($dynamicDataFlag['flagname'])){
                $flagname = explode("\n", $dynamicDataFlag['flagname']);
            }
            // P($flagname);

            // $member_ids = [];//为了下面存放会员ID  注释原因，不要调取会员数据，如果真要会员数据，前段自己上传，要不然太耗资源
            foreach($dynamicDataInfoList as $k => $v){
                /*整理标示*/
                if($flagname and $v['flagnum']){
                    // echo $v['flagnum'];
                    $dynamicDataInfoList[$k]['flagnum'] = Yii::$app->params['dynamicRule']['groupToOrigin'][$v['flagnum']-1];
                    // P($dynamicDataInfoList[$k]['flagnum'], false);
                    foreach($dynamicDataInfoList[$k]['flagnum'] as $k1 => $v1){
                        $index = array_search($v1, Yii::$app->params['dynamicRule']['origin']);
                        $dynamicDataInfoList[$k]['flag'][$k1] = $flagname[$index];
                    }
                    // echo Yii::$app->params['dynamicRule']['origin']
                }
                unset($dynamicDataInfoList[$k]['flagnum']);

                /*整理内容*/
                $dynamicDataInfoList[$k]['contents'] = [];
                foreach($v['content'] as $k1 => $v1){
                    foreach($v['attrName'] as $k2 => $v2){
                        if($v1['attr_enname'] == $v2['attr_enname']){
                            /*如果是图片，分割成数组*/
                            if($v['attrName'][$k2]['attr_type'] == 7 and !empty($v1['attr_value'])){
                                $val = explode(',', $v1['attr_value']);
                            }else{
                                $val = $v1['attr_value'];
                            }
                            $dynamicDataInfoList[$k]['contents'][$v1['attr_enname']] = $val;
                            // array_push($dynamicDataInfoList[$k]['contents'], [
                            //     $v1['attr_enname'] => $val,
                            // ]);
                        }
                    }
                }

                /*如果 member_id !=0 说明是需要会员登录，下面需要去除会员数据*/
                /* 注释原因，不要调取会员数据，如果真要会员数据，前段自己上传，要不然太耗资源
                if(!empty($v['member_id']) and !in_array($v['member_id'], $member_ids)){
                    array_push($member_ids, $v['member_id']);
                }
                */

                unset($dynamicDataInfoList[$k]['content']);
                unset($dynamicDataInfoList[$k]['attrName']);
            }
            // P($member_ids, false);

            /*如果动态数据需要会员信息的话，获取会员信息*/
            /* 注释原因，不要调取会员数据，如果真要会员数据，前段自己上传，要不然太耗资源
            if(!empty($member_ids)){
                // P($member_ids);
                $member = new Member(Yii::$app->params['ac']);
                $info = $member->getInfo($member_ids, $this->app_info_id);
                // P($info['data']);
                foreach($dynamicDataInfoList as $k => $v){
                    foreach($info['data'] as $k1 => $v1){
                        // P($info['data'][$k1]['member_id'], false);
                        if($v['member_id'] == $v1['member_id']){
                            unset($v1['member_id']);
                            $dynamicDataInfoList[$k]['member'] = $v1;
                        }
                    }

                    unset($dynamicDataInfoList[$k]['member_id']);
                }

            }
            */
            // P($dynamicDataInfoList);


            $res = array(
                'list' => $dynamicDataInfoList,
                'pageInfo' => array(
                    'count' => intval($count),
                    'currPage' => $currPage,
                    'pageSize' => $pageSize,
                ),
            );
            return Tool::showRes([0, '获取成功'], $res);
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*数据统计 比如满意度调查，返回数据格式为
    Array
    (
        [0] => Array
            (
                [attr] => 不满意
                [num] => 1
            )

        [1] => Array
            (
                [attr] => 很满意
                [num] => 2
            )

        [2] => Array
            (
                [attr] => 比较满意
                [num] => 1
            )

        [3] => Array
            (
                [attr] => 满意
                [num] => 1
            )
    )
    */
    public function actionStatistical()
    {
        if(isset($this->post['id']) 
            and is_numeric($this->post['id'])
            and isset($this->post['name'])){
            $sql = 'select attr_value as attr, count(*) num from {{%dynamic_data_list}} where info_id in (select info_id from {{%dynamic_data_info}} where dynamic_id = ' . $this->post['id'] .') and attr_enname = "' . $this->post['name'] . '" group by attr_value';
            // echo $sql;
            $res = DynamicDataList::findBySql($sql)->asArray()->all();
            // P($res);
            return Tool::showRes([0, '获取成功'], $res);
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*删除动态数据 只允许删除自己提交的数据*/
    public function actionDeleteDynamicData()
    {
        /*如果有openid, 则可以获取用户信息，实现登录*/
        if(!$this->isLogin() 
            and isset($this->get['openid'])){
            $this->getinfoByOpenid($this->get['openid'], $this->comid);
        }

        if($this->isLogin()){
            $id = isset($this->get['id'])?$this->get['id']:'';
            // echo $id;
            if($id){
                $dynamicDataInfo = DynamicDataInfo::find()->where(('info_id =:id and app_id = :appid and member_id = :mid'), [':id' => $id, ':appid' => $this->app_id, ':mid' => $this->memberInfo->member_id])->one();
                // P($dynamicDataInfo);
                if(!is_null($dynamicDataInfo)){
                    $dynamicDataInfo->state = 3;
                    if($dynamicDataInfo->save()){
                        $backInfo = ErrMap::getError(0, '删除我的动态数据成功');//返回信息
                        return Tool::showRes($backInfo);
                    }
                }
            }
        }else{//未登录
            list($errno, $errmsg) = ErrMap::getError(10007);
            return Tool::showRes([$errno, $errmsg]);
        }

        return Tool::showRes(ErrMap::getError(10005));

    }

}
